package com.wz.dhs.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wz.dhs.exception.BusinessException;
import com.wz.dhs.mapper.user.SysUserMapper;
import com.wz.dhs.model.common.BusinessCode;
import com.wz.dhs.po.user.SysUserEntity;
import com.wz.dhs.vo.login.LoginUserDetail;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @Author xyb
 * @Description //权限校验器
 * @Date 17:22 2022/7/13
 * @Param
 * @return
 **/
@Component
@RequiredArgsConstructor
public class SysUserDetailServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        SysUserEntity user = Optional.ofNullable(sysUserMapper.selectOne(new LambdaQueryWrapper<SysUserEntity>()
                        .eq(SysUserEntity::getPhone, phone)))
                .orElseThrow(() -> new UsernameNotFoundException("手机号不存在"));
        if(StringUtils.isBlank(user.getPassword())){
            throw new BusinessException(BusinessCode.USE_MINI_APP);
        }

        return new LoginUserDetail(user);
    }
}
